<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 * @author   howe <howe1995@163.com>
 */

namespace App\Middleware;

use App\Constant\ApiCodeEnum;
use App\Constant\Database\MessageEnum;
use App\Model\Friend;
use App\Repository\GroupUserRepository;
use App\Support\Traits\ServiceException;
use Hyperf\Context\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class MessageMiddleware implements MiddlewareInterface
{
    use ServiceException;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $method = $request->getMethod();
        if ($method == 'GET') {
            $params = $request->getQueryParams();
        } else {
            $params = $request->getParsedBody();
        }
        // $params = array_merge($post, $query);
        $toUser = $params['to_user'] ?? null;
        $isGroup = $params['is_group'] ?? null;
        $fromUser = auth()->user()->id;
        $assistantIds = get_assistant_ids();
        if (! in_array($isGroup, MessageEnum::IS_GROUP)) {
            $this->throwBusinessException(ApiCodeEnum::CLIENT_PARAMETER_ERROR);
        }
        if (! $toUser) {
            $this->throwBusinessException(ApiCodeEnum::CLIENT_PARAMETER_ERROR);
        }
        if ($isGroup == MessageEnum::GROUP) {
            // 校验是否群成员
            [$isGroupMember, $group] = GroupUserRepository::checkIsGroupMember($fromUser, $toUser, true);
            if (! $isGroupMember) {
                $this->throwBusinessException(ApiCodeEnum::SERVICE_GROUP_USER_NOT_EXISTS);
            }
            $from = [
                'id' => $fromUser,
                'nickname' => $group['nickname'] ?: auth()->user()->nickname,
                'avatar' => auth()->user()->avatar,
                'wechat' => auth()->user()->wechat,
            ];
        } else {
            // 好友校验 ai小助手不用校验
            $friend['nickname'] = auth()->user()->nickname;
            if (! in_array($toUser, $assistantIds)) {
                [$isFriend, $friend] = Friend::checkIsFriend($fromUser, $toUser, true);
                if (! $isFriend) {
                    $this->throwBusinessException(ApiCodeEnum::SERVICE_FRIEND_NOT_EXISTS);
                }
            }
            $from = [
                'id' => $fromUser,
                'nickname' => $friend['nickname'] ?: auth()->user()->nickname,
                'avatar' => auth()->user()->avatar,
                'wechat' => auth()->user()->wechat,
            ];
        }
        if ($method == 'GET') {
            $request = $request->withQueryParams(array_merge($params, compact('from')));
        } else {
            $request = $request->withParsedBody(array_merge($params, compact('from')));
        }
        Context::set(ServerRequestInterface::class, $request);
        return $handler->handle($request);
    }
}
